import { Request, Response, NextFunction, RequestHandler } from 'express'
import { fileFilter } from '../file/file.middleware'
import multer from 'multer'
import path from 'path'
import { Jimp } from 'jimp'

const fileUploadFilter = fileFilter(['image/jpeg', 'image/png', 'image/jpg'])

const avatarUpload = multer({
  dest: 'uploads/avatar',
  fileFilter: fileUploadFilter
})

export const avatarInerceptor: RequestHandler = avatarUpload.single('avatar')

export const avatarProcessor = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { file } = req
  const filePath = path.join(file.destination, 'resized', file.filename)
  const fileExt = file.mimetype.split('/')[1]

  try {
    const image = await Jimp.read(file.path)
    image.cover({ w: 256, h: 256 }).write(`${filePath}-large.${fileExt}`)
    image.cover({ w: 128, h: 128 }).write(`${filePath}-medium.${fileExt}`)
    image.cover({ w: 64, h: 64 }).write(`${filePath}-small.${fileExt}`)
  } catch (error) {
    next(error)
  }

  next()
}
